/*
    //post 请求
    this.$pollData(url, {}, (res) => {
        console.log(res)
    }, 5)
*/

class PollData {
  constructor(url, data) {
    return new Promise((resolve, rejects) => {
      api
        .post(url, data)
        .then(res => {
          resolve(res);
        })
        .catch(err => {
          rejects(err);
        });
    });
  }
}

Vue.prototype.$pollData = (url, data, callback, error, delay) => {
  delay = delay || 5;
  let timeout = null,
    isClose = false;
  let next = (/* url, data */) => {
      if (typeof url === "string") {
        return new PollData(url, data);
      } else {
        return new Promise((resolve, rejects) => {
          url(data, resolve, rejects);
        });
      }
    },
    start = fn => {
      fn(/* url, data */)
        .then(res => {
          callback && callback(res);
          timeout && clearTimeout(timeout);
          !isClose &&
            (timeout = setTimeout(() => {
              start(next);
            }, delay * 1000));
        })
        .catch(err => {
          timeout && clearTimeout(timeout);
          error && error(err);
        });
    };
  start(next);
  return {
    destroyed: () => {
      if (timeout) {
        clearTimeout(timeout);
        isClose = true;
      }
    }
  };
};

/*
  请求接口与参数
  postData:{
    url:'',
    data:{},
    time: 5
  }

  v-poll="请求接口及参数 | 成功回调 | 失败回调"

*/

Vue.directive("poll", {
  inserted: function(el, binding, vnode) {
    //console.log(el, binding, vnode.elm.__vue__);
    let a = binding.expression.split(
      " | "
    ); /* /\s*([^\(]+)\s*\(\s*([^,\)]+)\s*,\s*([^,\)]+)\s*\)/.exec(
      binding.expression
    ); */
    //console.log(a);
    let fn = a[1],
      err = a[2],
      params = a[0];
    let that = vnode.elm.__vue__;
    let poll = that.$pollData(
      /this\./.test(that[params].url)
        ? that[that[params].url]
        : that[params].url,
      that[params].data,
      res => {
        that[fn] && that[fn](res, poll);
      },
      error => {
        that[err] && that[err](error, poll);
      },
      that[params].time || 5
    );
  }
});